<script setup>
import { ref } from 'vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import { getUserAlumniEventService, deleteAlumniEventService } from '@/api/alumniEvent'
import { formatISOTime } from '@/utils/format'
import { getThisEventRegistrationRecordsService } from '@/api/registration'
import { ElMessage, ElMessageBox } from 'element-plus'
// 模拟数据
const tableData = ref([
  {
    eventName: '校友交流会',
    coverImageUrl: 'https://img0.baidu.com/it/u=2765486918,3196256426&fm=253&fmt=auto&app=120&f=JPEG?w=750&h=500',
    createTime: formatISOTime('2023-03-15'),
    startTime: formatISOTime('2023-04-01'), // 新增开始时间
    endTime: formatISOTime('2023-04-01'), // 新增开始时间
    publishStatus: '已发布',
    statusEnd: '进行中', // 新增活动状态,
    activityLocation: 'Zoom会议平台',
    viewCount: 100,
    reviewCount: 10,
    registrationCount: 10,
  },

])



// 筛选条件
const filters = ref({
  status: '',
  dateRange: [],
  keyword: ''
})

const statusOptions = ref([
  { label: '全部', value: '' },
  { label: '已发布', value: 'published' },
  { label: '草稿', value: 'draft' }
])

const jumpToEventDetail = (row) => {
  console.log('查看活动详情', row)
  // 使用查询参数形式传递eventId
  window.open(`/alumni-event/${row.eventId}`, '_blank')
}
const jumpTOEditEvent = (row) => {
  console.log('编辑活动', row)
  // 跳转到编辑页面，使用查询参数形式传递eventId
  window.open(`/publish-activity?eventId=${row.eventId}`, '_blank')

}

const jumpToReview = (row) => {
  console.log('查看活动回顾', row)
  // 新开浏览器标签页跳转到活动回顾页面
  window.open(`/event-review/${row.eventId}`, '_blank');
}

const resultTotalCount = ref(0)
const params = ref({
  eventName: '',
  publishStartTime: '',
  publishEndTime: '',
  publishStatus: '',
  page: 1,
  pageSize: 5,
})

const setRequestParams = () => {
  const { status, dateRange, keyword } = filters.value
  const statusMap = {
    '': '',
    published: 1,
    draft: 2
  }
  params.value.publishStatus = statusMap[status] || ''
  if (dateRange.length > 0) {
    params.value.publishStartTime = dateRange[0] ? formatISOTime(dateRange[0]) : ''
    params.value.publishEndTime = dateRange[1] ? formatISOTime(dateRange[1]) : ''
  }
  params.value.eventName = keyword || ''
  console.log('设置请求参数',params.value);
  //去除空字符串属性
  for (const key in params.value) {
    if (params.value[key] === '') {
      delete params.value[key]
    }
  }
}

const getUserAlumniEventData = async () => {
  setRequestParams()
  const { data } = await getUserAlumniEventService(params.value)
  // console.log(data);
  console.log('接收数据',data.records);
  const now = new Date()
  tableData.value = data.records.map(item => {

    const startTime = new Date(item.startTime)
    const endTime = new Date(item.endTime)

    let statusEnd = ''
    if (now < startTime) {
      statusEnd = '未开始'
    } else if (now > endTime) {
      statusEnd = '已结束'
    } else {
      statusEnd = '进行中'
    }

    return {
      ...item,
      createTime: formatISOTime(item.createTime),
      startTime: formatISOTime(item.startTime),
      endTime: formatISOTime(item.endTime),
      statusEnd,
      publishStatus: item.publishStatus === 1 ? '已发布' : '草稿'//1代表已发布,2代表草稿
    }
  })
  resultTotalCount.value = data.total

}

getUserAlumniEventData()

const handleReset = () => {
  filters.value = {
    status: '',
    dateRange: [],
    keyword: ''
  }
  params.value.eventName = '';
  params.value.publishStartTime = '';
  params.value.publishEndTime = '';
  params.value.publishStatus = '';
}

const onSizeChange = (size) => {
  params.value.page = 1; // 重新从第一页渲染
  params.value.pageSize = size; // 更新每页条数
  getUserAlumniEventData();
};

const onCurrentChange = (page) => {
  params.value.page = page; // 更新当前页
  getUserAlumniEventData();
};
const handlePublishStatusChange = () => {
  console.log('输出', filters.value);
}


// 在script部分添加以下变量
const dialogVisible = ref(false)
const registrationData = ref([])
const paramsRegistration = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 修改checkRegistration方法
const checkRegistration = async (row) => {
  dialogVisible.value = true
  const { data } = await getThisEventRegistrationRecordsService(row.eventId, {
    page: paramsRegistration.value.page,
    pageSize: paramsRegistration.value.pageSize
  })
  registrationData.value = data.records
  paramsRegistration.value.total = data.total
}

// 添加分页处理方法
const checkRegistrationPageChange = (page) => {
  paramsRegistration.value.page = page
  checkRegistration() // 需要传递当前活动ID，建议使用activeEventId变量缓存当前选中活动ID
}

// 修改删除方法
const deleteAlumniEvent = async (row) => {
  try {
    await ElMessageBox.confirm(
      '删除活动将同时清除活动回顾和所有报名记录，是否继续？',
      '警告',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
    )

    const { data } = await deleteAlumniEventService(row.eventId)
    ElMessage.success(data)
    getUserAlumniEventData() // 刷新数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

</script>

<template>
  <!-- <el-button type="primary" @click="setRequestParams">点击</el-button> -->
  <div class="content-manage">
    <!-- 标题 -->
    <h1 class="page-title">活动管理</h1>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <el-select v-model="filters.status" @change="handlePublishStatusChange" placeholder="发布状态" style="width: 120px">
        <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
      </el-select>

      <span class="filter-label  word-1">发布时间:</span>

      <el-date-picker v-model="filters.dateRange" class="date_picker" type="daterange" range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" />

      <el-input v-model.trim="filters.keyword" placeholder="搜索活动标题" style="width: 240px" clearable />

      <el-button type="primary" @click="getUserAlumniEventData">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="eventName" label="活动标题" width="100">
        <template #default="{ row }">
          <span class="event_title" @click="jumpToEventDetail(row)">{{ row.eventName }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="coverImageUrl" label="封面图片" width="180">
        <template #default="{ row }">
          <img :src="row.coverImageUrl" class="cover-image" alt="封面" />
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="发表时间" />
      <!-- 新增开始时间列 -->
      <el-table-column prop="startTime" label="开始时间" />
      <el-table-column prop="endTime" label="结束时间" />
      <el-table-column prop="activityLocation" label="活动地点" />


      <el-table-column prop="publishStatus" label="发表状态">
        <template #default="{ row }">
          <el-tag :type="row.publishStatus === '已发布' ? 'success' : 'info'">
            {{ row.publishStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 新增结束状态列 -->
      <el-table-column prop="statusEnd" label="活动状态">
        <template #default="{ row }">
          <el-tag :type="{
            '已结束': 'info',
            '进行中': 'success',
            '未开始': 'warning'
          }[row.statusEnd]">
            {{ row.statusEnd }}
          </el-tag>
        </template>
      </el-table-column>
       <!-- 新增浏览量列 -->
       <el-table-column prop="viewCount" label="浏览量" width="70">
        <template #default="{ row }">
          <span class="view-count">{{ row.viewCount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="101">
        <template #default="{ row }">
          <el-button type="primary" @click="jumpTOEditEvent(row)" :icon="Edit" circle />
          <el-button @click="deleteAlumniEvent(row)" type="danger" :icon="Delete" circle />
        </template>
      </el-table-column>
      <!-- 新增查看列 -->
      <el-table-column label="查看" width="120">
        <template #default="{ row }">
          <div class="view-btns">
            <el-button type="primary" size="small" @click="jumpToReview(row)">查看回顾：{{ row.reviewCount }}条</el-button>
            <el-button type="success" class="register_btn" size="small" @click="checkRegistration(row)">查看报名：{{ row.registrationCount }}人</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination background layout="jumper,total, sizes, prev, pager, next " :page-sizes="[2, 3, 5, 10]"
        size="large" v-model:current-page="params.page" v-model:page-size="params.pageSize" :total="resultTotalCount"
        @size-change="onSizeChange" @current-change="onCurrentChange" />
    </div>

  </div>

  <el-dialog v-model="dialogVisible"
  :close-on-click-modal="false" 
  title="报名情况" width="80%">
    <div class="registration-dialog">
      <div class="total-count">报名人数共 {{ paramsRegistration.total }} 人</div>

      <el-table :data="registrationData" border>
        <el-table-column prop="realName" label="姓名" />
        <el-table-column prop="userName" label="学工号" />
        <el-table-column prop="college" label="学院" width="200" />
        <el-table-column prop="major" label="专业" width="200" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="registrationTime" label="报名时间">
          <template #default="{ row }">
            {{ formatISOTime(row.registrationTime) }}
          </template>
        </el-table-column>
      </el-table>

      <el-pagination :current-page="paramsRegistration.page" :page-size="paramsRegistration.pageSize"
        :total="paramsRegistration.total" @current-change="checkRegistrationPageChange" layout="prev, pager, next"
        class="dialog-pagination" />
    </div>
  </el-dialog>

</template>

<style lang="scss" scoped>
.content-manage {
  padding: 20px;
  background: #fff;
  min-height: 100%;

  .page-title {
    margin-bottom: 20px;
    color: #333;
    font-size: 24px;
  }

  .filter-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    align-items: center;


    .filter-label {
      color: #61666d;
      // margin-right: 8px;
    }

    :deep(.el-date-editor) {
      flex: 0.5;
    }
  }

  .event_title {
    color: #61666d;

    &:hover {
      color: #409eff; // 悬停时变为蓝色
      text-decoration: underline; // 添加下划线
      cursor: pointer; // 鼠标变为手型
    }

  }

  :deep(.el-table__row) {
    .event_title {
      color: #61666d;

      &:hover {
        color: #409eff;
        text-decoration: underline;
        cursor: pointer;
      }
    }
  }

  .cover-image {
    width: 100px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
  }

  .view-btns {
    display: flex;
    flex-direction: column;
    gap: 8px;

    

    .el-button {
      width: 100%;
      .count-badge {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        background: #ff4d4f;
        color: white;
        border-radius: 10px;
        padding: 0 6px;
        font-size: 12px;
        line-height: 18px;
        min-width: 20px;
        text-align: center;
      }
    }.register_btn {
      margin-left: 0;
      .count-badge {
        background: #52c41a;
      }
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  :deep(.el-table__cell) {
    text-align: center;
  }
}

// 在style部分添加样式
.registration-dialog {
  .total-count {
    margin-bottom: 20px;
    font-size: 16px;
    color: #666;
  }

  .dialog-pagination {
    margin-top: 20px;
    justify-content: center;
  }

  :deep(.el-table__cell) {
    text-align: center;
  }
}
</style>